import { Component, OnInit, ViewChild } from '@angular/core';
import { NziModalService } from "ng-zorro-iop/modal/nzi-modal.service";
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute, Router } from "@angular/router";
import { FcsService } from "../../../service/fcs.service";
import { CommonService } from "../../../service/common.service";
import { FcsConfigComponent } from "../../../shared-component/fcs-config/fcs-config.component";
import { FcsPublishComponent } from "../../../shared-component/fcs-publish/fcs-publish.component";
import { Function, PublishVersionRes, VersionsGettingRes } from "../../../shared-component/class/instance";
import { FunctionCodeComponent } from "./code/function-code.component";
import { AliasCreateComponent } from "./alias/alias-create/alias-create.component";
import { AliasDeleteComponent } from "./alias/alias-delete/alias-delete.component";
import { NziTmsService } from 'ng-zorro-iop';
import { Environment } from '../../../../environments/environment';


@Component({
  selector: 'app-function-detail',
  templateUrl: './function-detail.component.html',
  styleUrls: ['./function-detail.component.less']
})
export class FunctionDetailComponent implements OnInit {
  @ViewChild('functionCodeComponent', { static: false }) functionCodeComponent: FunctionCodeComponent;

  nziResourceTags;
  nziTmsLoading = false;

  groupName = '';
  groupDisplayName = '';
  regionName = ''; //区域
  regionCode = 'cn-north-3';
  functionName = '';

  groupId = '';
  functionId = '';
  versionName = '';
  isLoading = true;
  data;
  statusMonitoringInterval = null;
  versionList = [];
  aliasList = [];
  functionStatus: string = '';
  disableConfig: boolean = false;
  disableOperation: boolean = false;
  disableConfigContent: string;
  disableOperationContent: string;
  disableFlowConfigContent: string;
  disableDeleteVersionContent: string;
  vpcList = [];
  RuntimeCustomContainer = "custom-container"
  constructor(
    private fcsService: FcsService,
    private modalService: NziModalService,
    private msgService: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private commonService: CommonService,
    private tmsService: NziTmsService

  ) { }

  ngOnInit() {
    this.groupId = this.activatedRoute.snapshot.params["groupId"];
    this.functionId = this.activatedRoute.snapshot.params["functionId"];
    this.versionName = this.activatedRoute.snapshot.params['versionName'];
    this.getFunctionDetail();
    //this.getVersions();
    this.getResourceTags();
  }

  //获取标签
  getResourceTags(){
    const serviceAPI = `${Environment.application.serviceAPI}`; // 从application.json读取serviceAPI
   
    this.nziTmsLoading = true;
    this.tmsService.getTagList('fcs').then((data) => {
      this.nziResourceTags = data;
      // console.log(this.nziResourceTags)
      this.nziTmsLoading = false;
    }, (error) => {
      this.nziTmsLoading = false;
    });
  }

  selectTabCode() {
    this.functionCodeComponent.selectTabCode();
  }

  async getVersions() {
    let versionsRes = await this.commonService.getVersionList(this.fcsService, this.groupId, this.functionId);
    if (versionsRes && versionsRes['success']) {
      this.versionList = versionsRes['versions'];
    }
    this.setDisableFlowAndDeleteVersion();
    //增加流量灰度属性
    let aliasRes = await this.commonService.getAliasList(this.fcsService, this.groupId, this.functionId);
    let aliasList = [];
    if (aliasRes && aliasRes['success']) {
      aliasList = aliasRes['alias'];
    }
    this.aliasList = aliasList;
    this.addFlowPercentToVersions();
  }

  addFlowPercentToVersions() {
    if (this.versionList && this.aliasList) {
      for (let i = 0; i < this.versionList.length; i++) {
        let versionName = this.versionList[i]['VersionName'];
        if (versionName === 'LATEST') {
          this.versionList[i]['flowPercent'] = ['默认流量: 100%'];
        } else {
          this.versionList[i]['flowPercent'] = [];
          for (let j = 0; j < this.aliasList.length; j++) {
            let aliasName = this.aliasList[j]['aliasName'];
            if (this.aliasList[j]['rule']['type'] === 'weight') {
              let trafficList = this.aliasList[j]['rule']['traffic'];
              if (trafficList) {
                for (let k = 0; k < trafficList.length; k++) {
                  if (trafficList[k]['versionName'] === versionName) {
                    this.versionList[i]['flowPercent'].push(`${aliasName}` + " : " + `${trafficList[k]['versionWeight']}` + "%");
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  ngOnDestroy() {
    this.doClearInterval();
  }

  doClearInterval() {
    clearInterval(this.statusMonitoringInterval);
    this.statusMonitoringInterval = null;
  }

  getFunctionDetailForStatus() {
    this.isLoading = true;
    this.fcsService.getFunctionDetail(this.groupId, this.functionId, this.versionName).subscribe(res => {
      res['envs'] = '';
      this.data = res;
      this.functionStatus = this.data.status;
      if (this.data.environment && this.data.environment.length > 0) {
        let len = this.data.environment.length;
        for (let i = 0; i < len; i++) {
          this.data['envs'] += this.data.environment[i]['key'] + '=' + this.data.environment[i]['value'] + ',';
        }
        this.data['envs'] = this.data['envs'].substring(0, this.data['envs'].length - 1);
      } else {
        this.data['envs'] = '--';
      }
      this.checkButtonStatus();
      this.isLoading = false;
    }, err => {
      this.isLoading = false;
    });
  }

  checkButtonStatus() {
    this.commonService.translateRuntime(this.data);
    if (this.data) {
      if (this.data.status === 'updating' || this.data.status === 'creating' || this.data.versionName !== 'LATEST') {
        this.disableConfig = true;
        if (this.data.versionName !== 'LATEST') {
          this.disableConfigContent = '非LATEST版本函数不支持配置';
        } else {
          if (this.data.status === 'creating') {
            this.disableConfigContent = '当前函数正在创建中，不支持配置';
          } else if (this.data.status === 'updating') {
            this.disableConfigContent = '当前函数正在更新中，不支持配置';
          }
        }
      } else {
        this.disableConfig = false;
      }
      if (this.data.status === 'updating' || this.data.status === 'creating') {
        this.disableOperation = true;
        if (this.data.status === 'creating') {
          this.disableOperationContent = '当前函数正在创建中，不支持操作';
        } else if (this.data.status === 'updating') {
          this.disableOperationContent = '当前函数正在更新中，不支持操作';
        }
      } else {
        // 只清理一次即可
        this.doClearInterval();
        this.disableOperation = false;
      }
    }
  }

  getFunctionDetail() {
    this.isLoading = true;
    this.fcsService.getFunctionDetail(this.groupId, this.functionId, this.versionName).subscribe(res => {
      this.isLoading = false;
      res['envs'] = '';
      this.data = res;
      this.groupName = this.data.groupName;
      this.groupDisplayName = this.data.groupDisplayName;
      this.regionName = this.data.regionName;
      this.regionCode = this.data.regionCode;
      this.functionName = this.data.functionName;
      this.data.functionName = this.data.functionName || '--';
      this.data.handler = this.data.handler || '--';
      if (this.data.environment && this.data.environment.length > 0) {
        let len = this.data.environment.length;
        for (let i = 0; i < len; i++) {
          this.data['envs'] += this.data.environment[i]['key'] + '=' + this.data.environment[i]['value'] + ',';
        }
        this.data['envs'] = this.data['envs'].substring(0, this.data['envs'].length - 1);
      } else {
        this.data['envs'] = '--';
      }
      // this.data.environment = this.data.environment || ['--'];
      this.checkButtonStatus();
      this.functionStatus = this.data.status;
      this.getVersions();
      this.isLoading = false;
      this.getVPCList();
      if (res && res.status) {
        let needMonitoring = (res.status === 'creating' || res.status === 'updating');
        if (needMonitoring) {
          if (!this.statusMonitoringInterval) {
            this.statusMonitoringInterval = setInterval(() => {
              this.getFunctionDetailForStatus();
            }, 5000);
          }
        } else {
          clearInterval(this.statusMonitoringInterval);
        }
      }

    }, error => {
      this.data = null;
      this.isLoading = false;
    })
  }

  getVPCList() {
    this.fcsService.getVPCList(this.regionCode).subscribe(res => {
      this.vpcList = [];
      if (res && res.vpcs) {
        this.vpcList = res.vpcs;
        let targetVPCs = this.vpcList.filter(item => item.vpc_id === this.data.vpcInfo['vpcId']);
        if (targetVPCs.length > 0) {
          this.data.vpcInfo['vpcName'] = targetVPCs[0].vpc_name || '';
          let subnets = targetVPCs[0].subnets || [];
          let targetSubnets = subnets.filter(item => item.subnet_id === this.data.vpcInfo['subnetId']);
          if (targetSubnets.length > 0) {
            this.data.vpcInfo['subnetName'] = targetSubnets[0].subnet_name || '';
          }
        }
      }
    }, err => {
      this.vpcList = [];
    })
  }

  editFunction(data) {
    data['groupDisplayName'] = this.groupDisplayName;
    this.modalService.create({
      nzTitle: '配置函数',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: FcsConfigComponent,
      nzComponentParams: { fcsInstance: data, regionCode: this.regionCode },
      nzOnOk: async createInstance => {
        let isSuccess = await createInstance.submitForm();
        isSuccess && this.getFunctionDetail();
        return isSuccess;
      },
    });
  }

  deleteFunction(data) {
    this.modalService.delete({
      nzTitle: '删除函数',
      nzContentTitle: `确定删除函数 <em>“${data.functionName}”</em> 吗？`,
      nzOnOk: () => {
        //返回一个promise对象才可以调用then等函数
        return new Promise((resolve, reject) => {
          this.fcsService.deleteFunction(data.groupId, data.functionId).subscribe(
            data => {
              if (data && data.code) {
                resolve(false);
                this.msgService.error(data.message || '删除失败！');
              } else {
                resolve(true);
                this.msgService.success('删除成功！');
                this.router.navigate(['/fcs-manage/function'])
              }
            },
            err => {
              resolve(false);
            }
          );
        });
      },
      nzCancelText: '取消',
      nzOnCancel: () => { },
    });
  }

  publishNewVersion(data) {
    if (this.functionStatus === 'updating') {
      return;
    }
    this.modalService.create({
      nzTitle: '发布新版本',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: FcsPublishComponent,
      nzComponentParams: { fcsInstance: data },
      nzOnOk: async createInstance => {
        let isSuccessObj: PublishVersionRes = await createInstance.submitForm();
        if (isSuccessObj.success) {
          this.versionName = isSuccessObj.versionName;
        }
        isSuccessObj.success && this.getFunctionDetail();
        return isSuccessObj.success;
      },
    });
  }

  choiceVersion(event, i) {
    if (i != undefined && i >= 0) {
      this.versionName = this.versionList[i].VersionName;
      this.getFunctionDetail();
    }
  }

  deleteVersion(event: MouseEvent, versionName) {
    event.stopPropagation();
    if (versionName === 'LATEST' || this.functionStatus === 'updating') {
      return;
    }
    this.modalService.delete({
      nzTitle: '删除函数版本',
      nzContentTitle: `确定删除函数版本 <em>“${versionName}”</em> 吗？`,
      nzOnOk: () =>{
        //返回一个promise对象才可以调用then等函数
        return new Promise((resolve, reject) =>{
          this.fcsService.deleteFunctionVersion(this.groupId, this.functionId, versionName).subscribe(
            res => {
                // if (this.versionName === versionName) {
                  this.versionName = 'LATEST';
                  resolve(true);
                  this.msgService.success('删除成功！');
                // }else{
                 
                //   resolve(false);
                //   this.msgService.error('删除失败！');
                  
                // }
                this.getVersions();
                this.getFunctionDetail();
          },
          err => {
            resolve(false);
          }
          )
        })
        
      },
      nzCancelText: '取消',
      nzOnCancel: () => { },
    });
   
  }

  tableOperateFunctionAlias(operation, data, event?: MouseEvent) {
    if (event) {
      event.stopPropagation();
    }
    this.operateFunctionAlias(operation, data);
  }

  operateFunctionAlias(operation, data) {
    let title: string;
    if (operation && operation === 'creation') {
      title = '创建别名';
    } else if (operation && operation === 'config') {
      title = '流量设置';
    }
    this.modalService.create({
      nzTitle: title,
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: AliasCreateComponent,
      nzComponentParams: { versionList: this.versionList, groupId: this.data.groupId, funcId: this.data.functionId, operation: operation },
      nzOnOk: async createInstance => {
        let isSuccess = await createInstance.submit();
        isSuccess && this.getVersions();
        return isSuccess;
      },
    });
  }

  changeData(val){
    if(val){
			this.getFunctionDetail();
		}
	}

  deleteFunctionAlias(data) {
    this.modalService.create({
      nzTitle: '删除别名',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: AliasDeleteComponent,
      nzComponentParams: { groupId: this.data.groupId, funcId: this.data.functionId },
      nzOnOk: async createInstance => {
        let isSuccess = await createInstance.submit();
        isSuccess && this.getVersions();
        return isSuccess;
      },
    });
  }

  setDisableFlowAndDeleteVersion() {
    for (let i = 0; i < this.versionList.length; i++) {
      if (this.versionList[i]['VersionName'] === 'LATEST') {
        this.versionList[i]['disableFlowConfigContent'] = 'LATEST版本不支持流量设置';
        this.versionList[i]['disableDeleteVersionContent'] = 'LATEST版本不支持删除';
      } else {
        if (this.functionStatus === 'updating') {
          this.versionList[i]['disableFlowConfigContent'] = '当前版本正在更新中，不支持流量设置';
          this.versionList[i]['disableDeleteVersionContent'] = '当前版本正在更新中，不支持删除';
        }
      }
    }
  }

  copySuccess() {
    this.msgService.success('复制成功!');
  }

  // ngAfterViewChecked () {
  //   let targetE = document.getElementsByClassName("cdk-overlay-container")[0];
  //   if(targetE){
  //     targetE['style'].cssText += "width:50%!important;left:unset;right:0!important;";
  //   }
  // }

}
